<template>
  <div class="assign-container">
    <el-page-header @back="goBack" content="分配跟进人" />
    
    <el-card class="assign-card">
      <!-- 项目信息展示 -->
      <div class="project-info">
        <h3>{{ project.projectName }}</h3>
        <el-tag>{{ project.status }}</el-tag>
      </div>
      
      <!-- 跟进人选择表单 -->
      <el-form :model="form" label-width="120px">
        <el-form-item label="选择跟进人" required>
          <el-select 
            v-model="form.followerId" 
            placeholder="请选择跟进人"
            filterable
            class="w-full"
          >
            <el-option
              v-for="follower in followers"
              :key="follower.id"
              :label="follower.name"
              :value="follower.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitAssign">确认</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage } from 'element-plus'
import axios from 'axios'

const api = axios.create({
  baseURL: `${import.meta.env.VITE_API_BASE_URL}`,
  timeout: 5000
})

const route = useRoute()
const router = useRouter()


// 表单数据
const form = ref({
  followerId: ''
})

// 获取项目数据
const project = ref({})
const followers = ref([])

onMounted(async () => {
  const id = route.query.id

  const { data: p } = await api.get(`/api/projects/${id}`)
  project.value = p


  followers.value = [
    { id: 1, name: '张三' },
    { id: 2, name: '李四' },
    { id: 3, name: '王五' }
  ]

  // 回显当前跟进人
  form.value.followerId = p.followerId || ''
})

// 提交分配

const submitAssign = async () => {
  if (!form.value.followerId) {
    ElMessage.warning('请选择跟进人')
    return
  }

  try {
    // 关键：只传要改的字段，后端已支持局部更新
    await api.put(`/api/projects/${project.value.id}`, {
      follower: followers.value.find(u => u.id === form.value.followerId)?.name || ''
    })

    ElMessage.success('分配成功')
    router.back()          // 返回上一页
  } catch (e) {
    ElMessage.error(`分配失败: ${e.message}`)
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}
</script>

<style scoped>
.assign-container {
  padding: 20px;
}
.assign-card {
  margin-top: 20px;
}
.project-info {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}
</style>